#!/bin/bash -eu
#
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

source /opt/c2d/c2d-utils || exit 1

# Get available system memory, div by 1024 to convert from kb -> mb, multiply
# by .8 to get 80% of that.
solr_memory_mb=$( awk '/MemAvailable/ { print int($2 / 1024 * .8) }' /proc/meminfo )

sed -i -e "s/^#SOLR_HEAP.*/SOLR_HEAP=\"${solr_memory_mb}m\"/" /etc/default/solr.in.sh

# Create realm.properties file for solr auth
readonly solr_pass="$(get_attribute_value "solr-admin-password")"

until curl -s -f http://localhost:8983; do
  sleep 3
done

curl --user admin:SolrRocks http://localhost:8983/api/cluster/security/authentication \
  -H 'Content-type:application/json' \
  -d "{\"set-user\": {\"admin\":\"${solr_pass}\"}}"
